package com.atguigu.gulimall.order.controller;

import com.atguigu.common.exception.NoStockException;
import com.atguigu.gulimall.order.entity.vo.OrderConfirmVo;
import com.atguigu.gulimall.order.entity.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.entity.vo.SubmitOrderResponseVo;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {

    @Autowired
    OrderService orderService;

    /**
     * 去结算页
     * @param model
     * @param request
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpServletRequest request) throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData",confirmVo);

        return "confirm";
    }

    /**
     * 下单功能
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes attributes){

        //下单：去创建订单 验令牌 验价格 锁库存。。。。。
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
            if (responseVo.getCode() == 0){
                //下单成功到支付选择页
                model.addAttribute("submitOrder",responseVo);
                return "pay";
            }else {
                String mag = "下单失败：";
                Integer code = responseVo.getCode();
                switch (code){
                    case 1: mag += "订单信息过期，请刷新再次提交"; break;
                    case 2: mag += "订单商品价格过期，请刷新确认再次提交"; break;
                    case 3: mag += "商品库存不足";
                }
                attributes.addFlashAttribute("msg",mag);
                //下单失败到订单确认页重新确认订单信息
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            if (e instanceof NoStockException){
                attributes.addFlashAttribute("msg","商品库存不足");
                //下单失败到订单确认页重新确认订单信息
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }

}
